import { router, pathMatchRegexp } from 'utils'
import api from 'api'
import store from 'store'
import { message } from 'antd';

const { loginUser } = api

export default {
  namespace: 'login',

  state: {},

  effects: {
    *login({ payload }, { put, call, select }) {
      const tdata = yield call(loginUser, payload)
      const data = tdata.result
      const { locationQuery } = yield select(_ => _.app)

      console.log('data.sessionToken:' + data.sessionToken)

      if (data.success) {
        store.set('mr-ly-sessionToken', data.sessionToken)
        sessionStorage.setItem('mr-ly-sessionToken-session', data.sessionToken)
        const { from } = locationQuery
        // console.log(JSON.stringify(locationQuery));
        let targetdashboard = data.dashboard ? data.dashboard : 'dashboard'
        yield put({ type: 'app/query' })
        if (from && !pathMatchRegexp('/login', from)) {
          if (from === '/') router.push(`/${targetdashboard}`)
          else router.push(from)
        } else { 
          router.push(`/${targetdashboard}`)
        }
      } else {
        console.log(JSON.stringify(data))
        throw data
      }
    },
  },
}
